package com.reason.common.interceptor;


import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * feign的拦截器，用于去除微服务之间的认证
 * @author  yulongjun
 * @date 2020/7/1 4:26 下午
 */
public class FeignInterceptor implements RequestInterceptor {


    /**
     * feign的拦截器传递令牌
     * @param requestTemplate
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {


        //获取请求资源
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        //不为空
        if(requestAttributes!=null){
            //获取当前线程的请求对象
            HttpServletRequest request=((ServletRequestAttributes)requestAttributes).getRequest();

            //如果request对象不为空
            if(request!=null){
                //得到所有请求头名称
                Enumeration<String> headerNames = request.getHeaderNames();

                while(headerNames.hasMoreElements()){
                    String header = headerNames.nextElement();
                    if("authorization".equals(header)){
                        //就是bearer jwt形式的值
                        String headerValue = request.getHeader(header);

                        //传递令牌
                        requestTemplate.header(header,headerValue);

                    }
                }

            }



        }


    }




}
